﻿using System;
using System.IO;

namespace ooWii.IO
{
	public class WbfsDiscInfo
	{
		#region WbfsDiscInfo

		string id;
		string name;
		Stream stream;
		byte[] blockMapBuffer;
		UInt32 blockSize;

		public WbfsDiscInfo( Stream stream, byte[] discinfo_buffer, byte[] blockMapBuffer, UInt32 blockSize )
		{
			this.stream = stream;

			id = WiiBuffer.GetString( discinfo_buffer, 0, 24 );
			name = WiiBuffer.GetString( discinfo_buffer, 32, 224 );
			this.blockMapBuffer = blockMapBuffer;
			this.blockSize = blockSize;
		}

		public string Id
		{
			get
			{
				return id;
			}
		}

		public string Name
		{
			get
			{
				return name;
			}
		}

		public Stream OpenRead()
		{
			SparseStream sparseStream = new SparseStream( stream );

			int wbfs_sec_max = 0;

			for( int wbfs_sec = 0; wbfs_sec < blockMapBuffer.Length / 2; wbfs_sec++ )
			{
				int physical_sec = WiiBuffer.GetUInt16( blockMapBuffer, wbfs_sec * 2 );
				if( physical_sec != 0 )
				{
					sparseStream.Map( (long)wbfs_sec * blockSize, (long)physical_sec * blockSize, blockSize );
					wbfs_sec_max = wbfs_sec;
				}
			}

			const long layerSize = 143432L * 0x8000;
			long length = wbfs_sec_max * blockSize;
			long layers = ( ( length + layerSize ) - 1 ) / layerSize;

			sparseStream.SetLength( layers * layerSize );

			return sparseStream;
		}

		#endregion
	}
}
